//
//  chuliListVC.m
//  运营管理系统
//
//  Created by 杨毅 on 16/9/29.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "chuliListVC.h"

@interface chuliListVC ()
{
    NSInteger userId;
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;
}
@property(strong,nonatomic) UITableView *listTableview;
@property(strong,nonatomic) NSMutableArray *dataList;
@property(nonatomic,strong) NSMutableArray *dataSource;
@property(nonatomic,strong) NSMutableArray *GZid;
@property(strong,nonatomic) AFHTTPSessionManager *manager;
@end

@implementation chuliListVC
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    NSString *doucumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //2.拼接上文件路径
    NSString *filtPath = [doucumentsPath stringByAppendingPathComponent:@"Log.txt"];
    //3.字典从文件中读取数据
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filtPath];
    if (dic != nil) {
        
        if (![[dic objectForKey:@"username"] isKindOfClass:[NSNull class]] && ![[dic objectForKey:@"password"] isKindOfClass:[NSNull class]]) {
            userId = [[dic objectForKey:@"userid"]integerValue];

        }else{
            //读取保存在中间对象中的数据
            UIApplication *app = [UIApplication sharedApplication];
            
            AppDelegate *delegate = app.delegate;
            
            //获取注册界面保存的数据
            userId = delegate.userId;
        }
    }

    [self setData];
}
- (AFHTTPSessionManager *)manager{
    
    if (!_manager) {
        
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"故障处理";
    self.view.backgroundColor=[UIColor whiteColor];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
}
//设置UI视图
-(void)initView
{
    self.listTableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH,kSCREEN_HEIGHT) style:UITableViewStylePlain];
    self.listTableview.backgroundColor = UIColorFromRGB(0xf0f0f0);
    self.listTableview.delegate=self;
    self.listTableview.dataSource=self;
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
   
    [self.listTableview setTableFooterView:v];
    [self.view addSubview:self.listTableview];
}

//数据
-(void)setData
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";

    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_chuliList parameters:@{userid:[NSString stringWithFormat:@"%ld",userId]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dicdate = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSDictionary *data = dicdate[@"data"];
        NSArray *arr = data[@"falist"];
       // NSLog(@"%@",dicdate);
        self.dataList=[NSMutableArray arrayWithCapacity:0];
        self.dataSource = [[NSMutableArray alloc]init];
        //_GZid = [[NSMutableArray alloc]init];
        for (NSInteger i = 0; i<arr.count; ++i) {
            
            NSString *strTime = [NSString stringWithFormat:@"%@",arr[i][@"occurT"]];
            
            NSString *Month_str = [strTime substringWithRange:NSMakeRange(5, 2)];
            NSString *Day_str = [strTime substringWithRange:NSMakeRange(8, 2)];
            NSString *Time = [NSString stringWithFormat:@"%@/%@",Month_str,Day_str];
            
            NSDictionary *dic=@{@"timeStr":Time,@"titleStr":arr[i][@"title"],@"averageScoreStr":arr[i][@"discrib"],@"state":arr[i][@"state"]};
            TimeModel *model=[[TimeModel alloc]initData:dic];
            [self.dataList addObject:model];
            canshuModel *model1 = [[canshuModel alloc]init];
            model1.Parid = [arr[i][@"id"]integerValue];
            model1.time = [NSString stringWithFormat:@"%@",arr[i][@"occurT"]];
            [self.dataSource addObject:model1];
        }
        if (self.dataSource.count == 0) {
            
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) title:@"没有要处理事件"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];
        }else{
            [self initView];
            [self.listTableview reloadData];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        if (status >= 500) {
            _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) AndTitle:[error userInfo][@"NSLocalizedDescription"]];
            _ServerFView.delegate = self;
            [self.view addSubview:_ServerFView];
        }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
            _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0,64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _Fallview.delegate = self;
            [self.view addSubview:_Fallview];
        }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
            _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _JoinFalutView.delegate = self;
            [self.view addSubview:_JoinFalutView];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];
 
}
- (void)NothingRefresh:(UIButton *)sender{
    [_nothing removeFromSuperview];
    [self setData];
}
-(void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self setData];
}
-(void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self setData];
}
-(void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self setData];
}
#pragma mark-----------------------------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId=@"testTime";
    RightSlidetableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell=[[RightSlidetableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    TimeModel *model=self.dataList[indexPath.row];
    [cell setData:model];
    //self.listTableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 62.0;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    canshuModel *model = _dataSource[indexPath.row];
    UIApplication *app = [UIApplication sharedApplication];
    
    AppDelegate *delegate = app.delegate;
    delegate.GZid = model.Parid;
    delegate.StarTime = model.time;
    GZchuliVC *vc = [[GZchuliVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
